import axios from "axios";
import { ElMessage } from "element-plus";
import { useAccountStore } from "@/store";

const service = axios.create({
  baseURL:
    import.meta.env.MODE === "development" ? "" : "http://119.29.244.79:8997",
  timeout: 100000,
  withCredentials: false,
});

// 拦截请求
service.interceptors.request.use(
  (config) => {
    const store = useAccountStore();
    if (store.authorization) {
      config.headers.Authorization = store.authorization;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 拦截响应
service.interceptors.response.use(
  // 响应成功进入第1个函数，该函数的参数是响应对象
  (response) => {
    const res = response.data;
    if (parseInt(res.code) === 200) return res;
    ElMessage.error(res?.msg || "请求出错");
    return Promise.reject(res);
  },
  // 响应失败进入第2个函数，该函数的参数是错误对象
  async (error) => {
    const user = useAccountStore();
    const { data, status } = error.response;
    if (status === 401) {
      user.clearToken();
      window.location.href = "/login";
      return;
    }
    ElMessage.error(data?.msg || error?.message || "请求出错");
    return Promise.reject(data);
  }
);

export default service;
